package com.zhaosc.elasticsearch;

import java.util.HashMap;

import org.apache.log4j.Logger;
import org.elasticsearch.action.bulk.BulkItemResponse;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.rest.RestStatus;
import org.junit.Test;

import com.google.common.collect.Maps;

/**
 * https://www.elastic.co/guide/en/elasticsearch/client/java-rest/7.5/java-rest-high-document-bulk.html
 * 
 * @author zhaosc
 *
 */
public class BulkTest extends BaseTest {

	private static final Logger logger = Logger.getLogger(BulkTest.class);

	/**
	 * 只支持 index，update，delete，即更新操作
	 */
	@Test
	public void testBulkIndex() {
		try {
			BulkRequest request = new BulkRequest();
			request.add(new IndexRequest(index).id("0001").source(XContentType.JSON, "field", "foo"));
			request.add(new DeleteRequest(index).id("0002"));
			request.add(new UpdateRequest(index,"0001").doc(XContentType.JSON,"field", "test"));
			BulkResponse bulkResponse = client.bulk(request, RequestOptions.DEFAULT);
			if (bulkResponse.status() == RestStatus.OK) {
				BulkItemResponse[] items = bulkResponse.getItems();
				for (BulkItemResponse item : items) {
					switch (item.getOpType()) {
				    case INDEX:    
				    case CREATE:
				        IndexResponse indexResponse = (IndexResponse) item.getResponse();
				        logger.info(indexResponse);
				        break;
				    case UPDATE:   
				        UpdateResponse updateResponse = (UpdateResponse) item.getResponse();
				        logger.info(updateResponse);
				        break;
				    case DELETE:   
				        DeleteResponse deleteResponse = (DeleteResponse) item.getResponse();
				        logger.info(deleteResponse);
				    }
					
					
				}

			}

		} catch (Exception e) {
			logger.error("",e);
		}
	}
	
}
